﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Collection.Entities;
using System.Collections.Specialized;
using System.IO;
using System.Threading;
using System.Net;
using System.Configuration;
using System.Drawing;
using WanPiJie.Products;
using WanPiJie.Img;

namespace Collection.Core.Processing
{
	public class ImageHandler
	{
		/// <summary>
		/// 下载图片
		/// </summary>
		public static void DownloadPicture(Action<string> callback)
		{
			int pageSize = 50;
			Int64 rowCount = ServiceFactory.MerchandiseService.Count;
			Int64 pageCount = rowCount / pageSize + ((rowCount % pageSize) > 0 ? 1 : 0);
			List<Merchandise> commodities;
			for (Int32 i = 1; i <= pageCount; i++)
			{
                commodities = ServiceFactory.MerchandiseService.GetMerchandises(i, pageSize);
				foreach (var merchandise in commodities)
				{
					DownloadPicture(merchandise, callback);
				}
			}
		}

		/// <summary>
		/// 下载图片
		/// </summary>
		/// <param name="merchandise">产品对象</param>
		/// <param name="callback">下载图片回调函数</param>
		public static void DownloadPicture(Merchandise merchandise, Action<string> callback)
		{
			var savePathConfig = (NameValueCollection)ConfigurationManager.GetSection("img/download");
			string basePath = savePathConfig["path"];
			basePath = Path.Combine(basePath, merchandise.CatalogId.ToString());
			var path = Path.Combine(basePath, string.Format("{0}.jpg", merchandise.Id.ToString()));
			if (File.Exists(path))
			{
				//可以做替换的处理
				callback(string.Format("图片：{0}—已存在，跳过！", path));
			}
			else
			{
				DownloadPicture(path, merchandise.Picture, 1000, callback);
			}
		}

		/// <summary>
		/// 下载图片
		/// </summary>
		/// <param name="filePath">文件保存路径</param>
		/// <param name="url">图片的url地址</param>
		/// <param name="callback">下载图片回调函数</param>
		private static void DownloadPicture(string filePath, string url, int millisecondsTimeout, Action<string> callback)
		{
			Thread.Sleep(millisecondsTimeout);
			try
			{
				ImageDownloader.Download(filePath, url);
				callback(string.Format("图片：{0}—下载完成！", filePath));
			}
			catch (WebException webException)
			{
				callback(string.Format("图片：{0}—下载异常（已经跳过）！", filePath));
				callback(string.Format("描述：{0}", webException.Message));
				HttpWebResponse response = webException.Response as HttpWebResponse;
				if (response == null || response.StatusCode != HttpStatusCode.NotFound)
				{
					callback(string.Format("重试时间：{0}秒", 10 * (millisecondsTimeout / 1000)));
					DownloadPicture(filePath, url, millisecondsTimeout * 10, callback);
				}
			}
		}

		/// <summary>
		/// 创建商品缩略图
		/// </summary>
		public static void CreateThumbnail(Action<string> callback)
		{
			int pageSize = 50;
            Int64 rowCount = ServiceFactory.MerchandiseService.Count;
			Int64 pageCount = rowCount / pageSize + ((rowCount % pageSize) > 0 ? 1 : 0);
			List<Merchandise> commodities;
			for (Int32 i = 1; i <= pageCount; i++)
			{
                commodities = ServiceFactory.MerchandiseService.GetMerchandises(i, pageSize);
				foreach (var merchandise in commodities)
				{
					CreateThumbnail(merchandise, callback);
				}
			}
		}

		/// <summary>
		/// 创建商品缩略图
		/// </summary>
		/// <param name="merchandise">商品</param>
		/// <param name="callback">缩略图回调</param>
		public static void CreateThumbnail(Merchandise merchandise, Action<string> callback)
		{
			var thumbnailConfig = (NameValueCollection)ConfigurationManager.GetSection("img/thumbnail");
			string originalImagePath = thumbnailConfig["fromPath"];
			string thumbnailPath = thumbnailConfig["toPath"];

			//原图片路径
			originalImagePath = Path.Combine(Path.Combine(originalImagePath
				, merchandise.CatalogId.ToString()), string.Format("{0}.jpg", merchandise.Id.ToString()));
			if (File.Exists(originalImagePath))
			{
				thumbnailPath = Path.Combine(Path.Combine(thumbnailPath,
					CategoryService.Instance.GetCatalogByThirdId(merchandise.CatalogId).Id.ToString()), merchandise.Id.ToString());
				if (!Directory.Exists(thumbnailPath))
				{
					Directory.CreateDirectory(thumbnailPath);
				}
				CreateThumbnail(originalImagePath, thumbnailPath, thumbnailConfig["sizePairs"].Split(';'), callback);
			}
		}

		/// <summary>
		/// 创建的缩略图
		/// </summary>
		/// <param name="originalImagePath">原图片路径</param>
		/// <param name="thumbnailPath"></param>
		/// <param name="sizePairs">图片尺寸对</param>
		/// <param name="callback"></param>
		private static void CreateThumbnail(string originalImagePath, string thumbnailPath, string[] sizePairs, Action<string> callback)
		{
			int width;
			int height;
			string savePath;
			string[] size;
			foreach (var sizePair in sizePairs)
			{
				size = sizePair.Split(',');
				width = int.Parse(size[0]);
				height = int.Parse(size[size.Length - 1]);
				savePath = Path.Combine(thumbnailPath, string.Format("{0}-{1}.jpg", width, height));
				if (File.Exists(savePath))
				{
					//可以考虑图片替换功能
					callback(string.Format("{0}—缩略图已存在，跳过！", thumbnailPath));
				}
				else
				{
					Handler.CreateThumbnailWithFilling(originalImagePath, savePath, width, height);
					callback(string.Format("{0}—缩略图生成！", thumbnailPath));
				}
			}
		}
	}
}
